<template>
  <div class="publish-page">
    <div class="content-container">
      <!-- 导航栏移到content-container内部 -->
      <div class="nav-header">
        <img src="../assets/icons/back.svg" class="back-icon" @click="goBack" />
        <span class="nav-title">委托发布</span>
        <BaseButton @click="goEditAddress">
          <PlusSquare class="icon-base" />
        </BaseButton>
      </div>

      <div class="form-container">
        <!-- 地址选择 -->
        <div class="form-section">
          <label for="departure">选择出发地</label>
          <div class="custom-select-wrapper" :data-open="departureDropdownOpen">
            <input
              type="text"
              class="custom-select-input"
              v-model="form.departure"
              @focus="toggleDepartureDropdown"
              placeholder="请选择或输入"
            />
            <div class="custom-select-dropdown" v-show="departureDropdownOpen">
              <div 
                v-for="option in addressOptions" 
                :key="option"
                class="item"
               @click="handleDepartureSelect(option)"
              >
                {{ option }}
              </div>
            </div>
          </div>
        </div>
  
        <div class="form-section">
          <label for="destination">选择目的地</label>
          <div class="custom-select-wrapper" :data-open="destinationDropdownOpen">
            <input
              type="text"
              class="custom-select-input"
              v-model="form.destination"
              @focus="toggleDestinationDropdown"
              placeholder="请选择或输入"
            />
            <div class="custom-select-dropdown" v-show="destinationDropdownOpen">
              <div 
                v-for="option in addressOptions" 
                :key="option"
                class="item"
                @click="handleDestinationSelect(option)"
              >
                {{ option }}
              </div>
            </div>
          </div>
        </div>
  
        <!-- 电话号码 -->
        <div class="form-section">
          <label for="phone">设置电话号码</label>
          <input type="tel" id="phone" v-model="form.phone" placeholder="请输入电话号码" />
        </div>
  
        <!-- 委托类型 -->
        <div class="white-panel">
          <div class="form-section">
            <label>委托类型</label>
            <div class="radio-group">
              <button :class="{'active': form.type === '外卖'}" @click="form.type = '外卖'">外卖</button>
              <button :class="{'active': form.type === '快递'}" @click="form.type = '快递'">快递</button>
            </div>
          </div>
        </div>
  
        <!-- 取件方式 -->
        <div class="white-panel">
          <div class="form-section">
            <label>取件方式</label>
            <div class="radio-group">
              <button :class="{'active': form.pickup === '定点存放'}" @click="form.pickup = '定点存放'">定点存放</button>
              <button :class="{'active': form.pickup === '当面交付'}" @click="form.pickup = '当面交付'">当面交付</button>
            </div>
          </div>
        </div>
  
        <!-- 物件大小 -->
        <div class="white-panel">
          <div class="form-section">
            <label>物件大小</label>
            <div class="radio-group">
              <button :class="{'active': form.size === '小'}" @click="form.size = '小'">小</button>
              <button :class="{'active': form.size === '中'}" @click="form.size = '中'">中</button>
              <button :class="{'active': form.size === '大'}" @click="form.size = '大'">大</button>
            </div>
          </div>
        </div>

        <!-- 组合的表单项面板 -->
        <div class="white-panel">
          <!-- 时间要求 -->
          <div class="form-section">
            <label for="time">时间要求</label>
            <input type="datetime-local" id="time" v-model="form.time" placeholder="请选择时间" />
          </div>
      
          <!-- 委托金额 -->
          <div class="form-section">
            <label for="amount">委托金额</label>
            <input type="number" id="amount" v-model="form.amount" placeholder="请输入金额" />
          </div>
      
          <!-- 委托备注 -->
          <div class="form-section">
            <label for="remark">委托备注</label>
            <textarea id="remark" v-model="form.remark" placeholder="请输入备注"></textarea>
          </div>
      
          <!-- 委托详细 -->
          <div class="form-section">
            <label for="details">委托详细(快递/外卖单号)</label>
            <textarea id="details" v-model="form.details" placeholder="请输入单号"></textarea>
          </div>
        </div>
  
        <!-- 图片上传 -->
        <div class="white-panel">
          <div class="form-section">
            <label>图片</label>
            <input type="file" @change="handleFileUpload" />
          </div>
        </div>
  
        <!-- 提交按钮 -->
        <button class="submit-button" @click="submitForm">发布委托</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { PlusSquare } from 'lucide-vue-next';
import BaseButton from '@/components/BaseButton.vue';

const router = useRouter();

// 表单初始值
const form = ref({
  departure: '',
  destination: '',
  phone: '',
  type: '外卖',
  pickup: '定点存放',
  size: '小',
  time: new Date().toISOString().slice(0, 16), // 设置为当前时间
  amount: '10',
  remark: '请尽快送达',
  details: 'SF1234567890',
  image: null,
});

// 添加下拉选项数据
const addressOptions = ['榕园', '荔园', '槿园','华夏门']

// 添加下拉框控制状态
const departureDropdownOpen = ref(false)
const destinationDropdownOpen = ref(false)

// 添加切换函数
function toggleDepartureDropdown() {
  departureDropdownOpen.value = !departureDropdownOpen.value
  destinationDropdownOpen.value = false // 关闭另一个下拉框
}

function toggleDestinationDropdown() {
  destinationDropdownOpen.value = !destinationDropdownOpen.value
  departureDropdownOpen.value = false // 关闭另一个下拉框
}

function handleDepartureSelect(option) {
  form.value.departure = option
  departureDropdownOpen.value = false
}

function handleDestinationSelect(option) {
  form.value.destination = option
  destinationDropdownOpen.value = false
}

// 添加点击外部关闭下拉框
onMounted(() => {
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.custom-select-wrapper')) {
      departureDropdownOpen.value = false
      destinationDropdownOpen.value = false
    }
  })
})

// 当前用户 ID
const currentUserId = JSON.parse(localStorage.getItem('user'));

function goBack() {
  router.push('/');
}

const goEditAddress = () => {
  router.push('/Publish/address');
};

const submitForm = async () => {
  try {
    if (!form.value.departure || !form.value.destination || !form.value.phone || 
        !form.value.time || !form.value.amount || !form.value.type || 
        !form.value.pickup || !form.value.size) {
      alert('请填写必要的表单信息！');
      return;
    }

    // 格式化时间字符串，添加秒和时区信息
    const formattedTime = new Date(form.value.time).toISOString();

    const formData = new FormData();
    
    // 获取当前用户ID
    const currentUser = JSON.parse(localStorage.getItem('user'));
    if (!currentUser || !currentUser.uid) {
      alert('请先登录！');
      router.push('/login');
      return;
    }

    // 添加表单数据
    formData.append('s_uid', currentUser.uid);
    formData.append('pickup_type', form.value.type === '外卖' ? 2 : 1);
    formData.append('pickup_method', form.value.pickup === '当面交付' ? 1 : 2);
    formData.append('pickup_address', form.value.departure);
    formData.append('delivery_address', form.value.destination);
    formData.append('size', form.value.size === '小' ? 1 : form.value.size === '中' ? 2 : 3);
    formData.append('limit_time', formattedTime); // 使用格式化后的时间
    formData.append('phone_number', form.value.phone);
    formData.append('total_amount', form.value.amount);
    
    // 可选字段
    if (form.value.remark) formData.append('remarks', form.value.remark);
    if (form.value.details) formData.append('detail', form.value.details);
    if (form.value.image) formData.append('img', form.value.image);

    const response = await fetch('/api/auth/com-release', {
      method: 'POST',
      headers: {
        'Authorization': localStorage.getItem('token')
      },
      body: formData
    });

    const data = await response.json();
    
    if (data.code === 0) {
      alert('委托发布成功！');
      router.push('/');
    } else {
      throw new Error(data.message || '发布失败');
    }
  } catch (error) {
    console.error('发布委托错误:', error);
    alert(error.message || '发布失败，请重试');
  }
};

const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 保存文件对象以供后续提交
  form.value.image = file;
};

// 添加加载默认地址的方法
const loadDefaultAddress = async () => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser?.uid;

    if (!userId) {
      console.error('未找到用户ID');
      return;
    }

    const response = await axios.get('/api/auth/addresses', {
      params: { uid: userId },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
      }
    });

    if (response.data.code === 0 && response.data.data?.addresses) {
      const defaultAddress = response.data.data.addresses.find(addr => addr.IsPrimary == 1);
      
      
      if (defaultAddress) {
        form.value.departure = defaultAddress.PickupAddress;
        form.value.destination = defaultAddress.DeliveryAddress;
        form.value.phone = defaultAddress.PhoneNumber;
      }
    }
  } catch (error) {
    console.error('加载默认地址失败:', error);
  }
};

onMounted(() => {
  // 检查是否有选中的地址信息
  const selectedAddress = localStorage.getItem('selectedAddress');
  console.log(selectedAddress);
  if (selectedAddress) {
    const address = JSON.parse(selectedAddress);
    form.value.departure = address.from;
    form.value.destination = address.to;
    form.value.phone = address.phone;
    // 清除localStorage中的数据
    localStorage.removeItem('selectedAddress');
  } else {
    // 如果没有选中的地址，则加载默认地址
    loadDefaultAddress();
  }

  // 原有的事件监听器
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.custom-select-wrapper')) {
      departureDropdownOpen.value = false;
      destinationDropdownOpen.value = false;
    }
  });
});
</script>

<style scoped>
.publish-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #9dbce3 0%, #ffffff 100%) fixed;
  background-size: 100% 150vh; /* 设置渐变的绝对高度 */
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
}

.content-container {
  min-height: 100%; /* 确保内容容器至少与视口一样高 */
  padding: 20px;
}

.nav-header {
  height: 61px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  position: relative;
  margin-bottom: 20px;
  /* 移除背景色，让渐变显示 */
  background: transparent;
}

.back-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
  position: absolute;
  left: 10px;
  filter: brightness(0) invert(1);  /* 添加这行来将图标改为白色 */
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 22px;
  font-weight: 500;
  font-family: "SourceHanFontBold";
  color: #ffffff;  /* 修改为白色 */
}

.form-container {
  /* padding: 16px; */
}

.form-section {
  margin-bottom: 20px;
}

label {
  display: block;
  font-weight: 500;  /* 改为更细的字重 */
  margin-bottom: 12px;
  color: #333;
  font-size: 18px;
}

input, select, textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  background-color: #fff;
  color: #333; /* 设置字体颜色 */
}

textarea {
  resize: none;
}

.radio-group button {
  width: 90px;
  margin-right: 8px;
  padding: 4px 0;  /* 修改内边距以适应固定宽度 */
  border: none;  /* 移除边框 */
  border-radius: 15px;  /* 修改按钮圆角为15px */
  background: #eeeeee;  /* 默认背景色 */
  color: #5b5b5b;  /* 默认文字颜色 */
  cursor: pointer;
  text-align: center;  /* 确保文字居中 */
  font-size: 14px;
}

.radio-group button.active {
  background: #a7c9e1;
  color: #fff;
  border: none;  /* 确保激活状态也没有边框 */
}

.submit-button {
  width: 100%;
  padding: 12px;
  margin-top: 50px;
  margin-bottom: 100px;
  background: #a7c9e1;
  color: #fff;
  border: none;
  border-radius: 15px;  /* 修改提交按钮圆角为15px */
  font-size: 16px;
  cursor: pointer;
}

/* 添加自定义下拉框样式 */
.custom-select-wrapper {
  position: relative;
  width: 100%;
}

.custom-select-display {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #ffffff;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  position: relative;
  transition: all 0.2s ease;
}

.custom-select-wrapper[data-open="true"] .custom-select-display {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-color: transparent;
}

.custom-select-display::after {
  content: "";
  position: absolute;
  right: 15px;
  top: 50%;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #666;
  transform: translateY(-50%);
}

.custom-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  margin-top: 0;
  z-index: 999;
  max-height: 200px;
  overflow-y: auto;
}

.custom-select-dropdown .item {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.custom-select-dropdown .item:hover {
  background: #f5f7fa;
}

/* 修改下拉框输入框样式 */
.custom-select-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #ffffff;
  font-size: 14px;
  color: #333;
  position: relative;
  transition: all 0.2s ease;
}

.custom-select-wrapper[data-open="true"] .custom-select-input {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-color: transparent;
}

/* 修改前三个表单项的标签颜色 */
.form-section:nth-child(-n+3) label {
  color: #ffffff;
}

/* 修改前三个表单项的文本显示颜色 */
.form-section:nth-child(-n+3) .custom-select-display,
.form-section:nth-child(-n+3) input {
  color: #5b5b5b;  /* 修改文字颜色为灰色 */
  background: #ffffff;  /* 修改背景为白色 */
  border-color: rgba(255, 255, 255, 0.8);
}

/* 修改placeholder的颜色 */
.form-section:nth-child(-n+3) input::placeholder {
  color: #5b5b5b;
}

/* 下拉框中的"请选择"文字颜色 */
.form-section:nth-child(-n+3) .custom-select-display {
  color: #5b5b5b;
}

/* 修改下拉选项的颜色保持黑色，确保可读性 */
.custom-select-dropdown .item {
  color: #333;
}

/* 添加白色半透明面板样式 */
.white-panel {
  width: 350px;
  margin-left: auto;
  margin-right: auto;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 15px;  /* 修改圆角为20px */
  padding: 15px;
  margin-bottom: 20px;
}

/* 调整在白色面板内的表单部分的边距 */
.white-panel .form-section {
  margin-bottom: 0;
}

/* 修改白色面板内的标签颜色 */
.white-panel .form-section label {
  color: #5b5b5b;
}

/* 修改白色面板内的表单边距 */
.white-panel .form-section:not(:last-child) {
  margin-bottom: 15px;  /* 给面板内的表单项之间添加间距 */
}

.white-panel .form-section:last-child {
  margin-bottom: 0;  /* 最后一个表单项不需要底部边距 */
}

/* 修改白色面板内的输入框样式 */
.white-panel input {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 10px 15px;  /* 统一内边距 */
  font-size: 14px;
}

/* 修改白色面板内的输入框样式 */
.white-panel .form-section input[type="datetime-local"],
.white-panel .form-section input[type="number"] {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 10px 15px;
  font-size: 14px;
  width: 100%;
  background-color: #ffffff;
  color: #5b5b5b;
}

/* 确保文本框样式统一 */
.white-panel .form-section textarea {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 10px 15px;
  font-size: 14px;
  width: 100%;
  background-color: #ffffff;
  color: #5b5b5b;
}
</style>
